The Python SDK tries to make it easy to make requests to the Box API.

Part of the ease is the fact that the SDK handles the OAuth2 dance, including token refresh, even for multithreaded applications.

New to the SDK are some OAuth2 subclasses and mixins that enable the SDK to handle auth in a variety of advanced use cases:

  • Cooperative multiprocessing - share token pairs across python processes
  • Remote auth - make API requests on a local client, but handle auth on a remote server to avoid exposing a client secret on clients
  • Distributed cooperative multiprocessing - store token pairs in Redis; share among multiple processes or machines

In [3]:
from boxsdk import Client
from boxsdk.auth.redis_managed_oauth2 import RedisManagedOAuth2

In [1]:
# Get a client ID and secret from a text file (to avoid exposing them in the notebook)
with open('secrets.txt') as secrets:
    client_id = secrets.readline().strip()
    client_secret = secrets.readline().strip()

In [5]:
# Instantiate a redis managed auth client
auth = RedisManagedOAuth2(client_id=client_id, client_secret=client_secret)

In [10]:
# Authenticate the instance using an auth code (obtained manually)
auth.authenticate(auth_code='thZWxpiTRPhJpqZRNidr1vZLsmWpHRLI')


Out[10]:
(u'g9katDPiv0C5DxcoDmzxxFzumMKpiH2z',
 u'pvGLrhHFdd70Ka7kPY1xxSAQ5RHAWrZBAuA4zbimV1o2Xrouvu0Ixl7iCERU7yTw')

The auth instance automatically saves the tokens to redis.

We can see the values directly in redis.


In [13]:
!redis-cli hvals {str(auth.unique_id)}


1) "g9katDPiv0C5DxcoDmzxxFzumMKpiH2z"
2) "pvGLrhHFdd70Ka7kPY1xxSAQ5RHAWrZBAuA4zbimV1o2Xrouvu0Ixl7iCERU7yTw"

In [15]:
auth.access_token


Out[15]:
u'g9katDPiv0C5DxcoDmzxxFzumMKpiH2z'

We can spin up another auth instance that will share tokens.

We just need to use the same unique id.


In [16]:
auth2 = RedisManagedOAuth2(client_id=client_id, client_secret=client_secret, unique_id=auth.unique_id)
auth2.access_token


Out[16]:
'g9katDPiv0C5DxcoDmzxxFzumMKpiH2z'

In [ ]: